package com.medical.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.medical.entity.IdCardRoot;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
@RequestMapping("/idCard")
public class IDCartController {

    public static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI5tSAEHKaorEauerTDPhU")
                .setAccessKeySecret("SonT2i8OwtZtLqJK7BMFPnXOCex6ro");
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        //设置阿里云 OCR 服务的 API 终端地址。
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }

    @SneakyThrows
    @RequestMapping("getIdCard")
    public Object getOcrInfo(@RequestParam("file") MultipartFile file) throws Exception {
        Client client = IDCartController.createClient();
        //将fille文件转化为stream流
        InputStream bodyStream = file.getInputStream();

        RecognizeIdcardRequest recognizeIdcardRequest = new RecognizeIdcardRequest();
        recognizeIdcardRequest.setBody(bodyStream);
        RecognizeIdcardResponse response = null;
        String data = "";
        IdCardRoot idCardRoot = null;
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            response = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);

            RecognizeIdcardResponseBody body = response.getBody();
            data = body.getData();
            idCardRoot = JSON.parseObject(data, IdCardRoot.class);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
        }

        return idCardRoot;

    }

}
